package org.example.doubleFinger;

import java.util.ArrayList;
import java.util.List;

public class Sum_of_Four_Numbers {
    public static void main(String[] args) {
        //四数之和

        //给你一个由 n 个整数组成的数组 nums ，和一个目标值 target 。请你找出并返回满足下述全部条件且不重复的四元组 [nums[a], nums[b], nums[c], nums[d]] （若两个四元组元素一一对应，则认为两个四元组重复）：
        int[] nums = {2,2,2,2,2};
        int target = 8;

        System.out.print("[ ");
        for (List<Integer> list : fourSum1(nums,target)) {
            System.out.print("[ ");
            for (Integer i : list) {
                System.out.print(i+" ");
            }
            System.out.print("],");
        }
        System.out.print("],");

    }
    public static List<List<Integer>> fourSum1(int[] nums, int target) {
        nums = sort(nums);
        ArrayList<List<Integer>> arrayList = new ArrayList<>();
        for (int i = 0; i < nums.length; i++) {
            if (nums[i]>0 && nums[i] > target){
                return arrayList;
            }
            if (i!=0 && nums[i]==nums[i-1]){
                continue;
            }
            for (int j = i+1; j < nums.length; j++) {
                int sum12 = nums[i] + nums[j];
                if (sum12>0 && sum12>target){
                    break;
                }
                if (j!=i+1 && nums[j]==nums[j-1]){
                    continue;
                }
                int left = j+1;
                int right = nums.length-1;
                int sum ;
                while(left<right){
                    sum = nums[i] + nums[j] + nums[left] + nums[right];
                    if (sum==target){
                        ArrayList<Integer> list = new ArrayList<>();
                        list.add(nums[i]);
                        list.add(nums[j]);
                        list.add(nums[left]);
                        list.add(nums[right]);
                        arrayList.add(list);
                        left++;
                        right--;
                        while(left<right  && nums[left-1] == nums[left]){
                            left++;
                        }
                        while(left<right  && nums[right] == nums[right+1]){
                            right--;
                        }
                    } else if (sum < target) {
                        left++;
                    }else{
                        right--;
                    }
                }
            }
        }
        return arrayList;
    }
    public static int[] sort(int[] nums){
        int temp;
        for (int i = 0; i < nums.length; i++) {
            for (int j = 0; j < nums.length - 1 - i; j++) {
                if (nums[j]>nums[j+1]){
                    temp = nums[j];
                    nums[j] = nums[j+1];
                    nums[j+1] = temp;
                }
            }
        }
        return nums;
    }
}
